package com.suanfa.island;

/**
 * 给定二维数组中最大岛屿的面积
 */
public class MaxArea {

    public static void main(String[] args) {
        int[][] arr={{0,0,1,0,0,0,0,1,0,0,0,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,1,1,0,1,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,1,0,0},{0,1,0,0,1,1,0,0,1,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,1,1,0,0,0,0}};
        System.out.println(getMax(arr));
        int[][] arr1={{0,0,1,0,0,0,0,1,0,0,0,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,1,1,0,1,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,1,0,0},{0,1,0,0,1,1,0,0,1,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,1,1,0,0,0,0}};

        System.out.println(maxAreaOfIsland(arr1));
    }



    public static int getMax(int[][] arr){
        int  max = 0;
        for(int r =0; r<arr.length; r++){
            for(int c=0; c<arr[0].length; c++){
                if(arr[r][c] == 1) {
                    int area = area(arr, r, c);
                    max = Math.max(area, max);
                }
            }
        }
        return  max;


    }

    static int area(int[][] arr, int r, int c){
        if(!inArea(arr, r, c)){
            return 0;
        }
        if(arr[r][c] != 1){
            return 0;
        }
        arr[r][c] = 2;
        return 1
                + area(arr,r+1, c)
                + area(arr,r-1, c)
                + area(arr,r, c+1)
                + area(arr,r, c-1);
    }

    public static boolean inArea(int[][] arr, int r, int c){
       return c>=0 && r>=0 && r< arr.length && c< arr[0].length;
    }


    public static int maxAreaOfIsland(int[][] grid) {
        int res = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {
                    int a = area1(grid, r, c);
                    res = Math.max(res, a);
                }
            }
        }
        return res;
    }

    static int area1(int[][] grid, int r, int c) {
        if (!inArea1(grid, r, c)) {
            return 0;
        }
        if (grid[r][c] != 1) {
            return 0;
        }
        grid[r][c] = 2;

        return 1
                + area1(grid, r - 1, c)
                + area1(grid, r + 1, c)
                + area1(grid, r, c - 1)
                + area1(grid, r, c + 1);
    }

    static boolean inArea1(int[][] grid, int r, int c) {
        return 0 <= r && r < grid.length
                && 0 <= c && c < grid[0].length;
    }
}
